import { Message } from "element-ui";
import threeLevel from "@/assets/countryLevel3";
/** *
 * 生成从minNum到maxNum的随机数
 * @parmas minNum 最小数
 * @parmas maxNum 最大数
 */
export function getRandomNum(minNum, maxNum) {
	switch (arguments.length) {
		case 1:
			return parseInt(Math.random() * minNum + 1, 10);
		case 2:
			return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
		default:
			return 0;
	}
}

/** *
 * 格式化data-text数据
 * @parmas keyData 列表数据源
 * @parmas data 匹配的数据
 */
export function formatReport(keyData = [[]], data = {}) {
	keyData.forEach(clilderArr => {
		clilderArr.forEach(e => {
			Object.keys(data).forEach(fKey => {
				if (e.key == fKey) {
					e.value = data[fKey];
				}
			});
		});
	});

	return keyData;
}
export function delKey(obj, ...args) {
	args.forEach(k => {
		delete obj[k];
	});
	return obj;
}

export function delEmptyChildren(list = [], key = "children") {
	function deep(arr = []) {
		arr.forEach(v => {
			let children = v[key] ?? [];
			if (!children.length) {
				delete v[key];
				return;
			}
			deep(children);
		});
	}
	deep(list);
	return list;
}
export function showFormErr(errors) {
	if (!errors) return;
	let msgs = Object.values(errors).map(v => v[0]);
	if (msgs.length) {
		Message.warning(msgs[0].message);
	}
	return msgs;
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
	return !!ele.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
	if (!hasClass(ele, cls)) ele.className += " " + cls;
}

/* istanbul ignore next */
export function removeClass(el, cls) {
	if (!el || !cls) return;
	var classes = cls.split(" ");
	var curClass = " " + el.className + " ";

	for (var i = 0, j = classes.length; i < j; i++) {
		var clsName = classes[i];
		if (!clsName) continue;

		if (el.classList) {
			el.classList.remove(clsName);
		} else if (hasClass(el, clsName)) {
			curClass = curClass.replace(" " + clsName + " ", " ");
		}
	}
	if (!el.classList) {
		el.className = trim(curClass);
	}
}

/**
 * @param {HTMLElement} element
 * @param {string} event
 * @param {function} handler
 */
export const on = (function () {
	if (document.addEventListener) {
		return function (element, event, handler) {
			if (element && event && handler) {
				element.addEventListener(event, handler, false);
			}
		};
	} else {
		return function (element, event, handler) {
			if (element && event && handler) {
				element.attachEvent("on" + event, handler);
			}
		};
	}
})();
/**
 * @param {HTMLElement} element
 * @param {string} event
 * @param {function} handler
 */
export const off = (function () {
	if (document.removeEventListener) {
		return function (element, event, handler) {
			if (element && event) {
				element.removeEventListener(event, handler, false);
			}
		};
	} else {
		return function (element, event, handler) {
			if (element && event) {
				element.detachEvent("on" + event, handler);
			}
		};
	}
})();

/**
 * @param {HTMLElement} el
 * @param {string} event
 * @param {function} fn
 */
export const once = function (el, event, fn) {
	let listener = function () {
		if (fn) {
			fn.apply(this, arguments);
		}
		off(el, event, listener);
	};
	on(el, event, listener);
};
export function uniqBy(arr, predicate) {
	const cb = typeof predicate === "function" ? predicate : o => o[predicate];

	return [
		...arr
			.reduce((map, item) => {
				const key = item === null || item === undefined ? item : cb(item);
				map.has(key) || map.set(key, item);
				return map;
			}, new Map())
			.values()
	];
}

// 快捷生成target列表
export function getTargetRows(data = []) {
	if (!data.length) return [];
	let result = [];
	function deep(arr = [], i, list) {
		for (let j = 0; j < list[i].length; j++) {
			if (i < list.length - 1) {
				arr[i] = list[i][j];
				deep(arr, i + 1, list); // 递归循环
			} else {
				result.push([...arr, list[i][j]]); // 扩展运算符，连接两个数组
			}
		}
	}
	deep([], 0, data);
	return result;
}

export function pageList(pageNo, pageSize, list) {
	let offset = (pageNo - 1) * pageSize;
	return offset + pageSize >= list.length
		? list.slice(offset, list.length)
		: list.slice(offset, offset + pageSize);
}

// 递归查询
export function deepSearch(tree, search, Key = "name") {
	let isGet = false;
	let retNode = {};
	function deep(tree) {
		for (let i = 0; i < tree.length; i++) {
			if (tree[i].children && tree[i].children.length > 0) {
				deep(tree[i].children);
			}
			if (search === tree[i][Key] || isGet) {
				isGet || (retNode = tree[i]);
				isGet = true;
				break;
			}
		}
	}
	deep(tree);
	return retNode;
}
export function uuid() {
	let d = new Date().getTime();
	let uuid = "xxxxxxxxxxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, c => {
		let r = (d + Math.random() * 16) % 16 | 0;
		d = Math.floor(d / 16);
		return (c == "x" ? r : (r & 0x3) | 0x8).toString(16);
	});
	return uuid;
}

export function toChinesNum(num) {
	let changeNum = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
	let unit = ["", "十", "百", "千", "万"];
	num = parseInt(num);
	function getWan(temp) {
		let strArr = temp
			.toString()
			.split("")
			.reverse();
		let newNum = "";
		for (let i = 0; i < strArr.length; i++) {
			newNum =
				(i == 0 && strArr[i] == 0
					? ""
					: i > 0 && strArr[i] == 0 && strArr[i - 1] == 0
						? ""
						: changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i])) + newNum;
		}
		return newNum;
	}
	let overWan = Math.floor(num / 10000);
	let noWan = num % 10000;
	if (noWan.toString().length < 4) {
		noWan = "0" + noWan;
	}
	return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);
}

/**
 * 多维数组转成一维数组
 * @param arr 原始数组
 * @param key 子集的key标识
 */
export function flatten(arr, key = "children") {
	return arr.reduce((prev, next) => {
		return prev.concat(Array.isArray(next[key]) ? flatten(next[key]) : next);
	}, []);
}

export function scrollIntoView(container, selected) {
	if (!selected) {
		container.scrollTop = 0;
		return;
	}

	const offsetParents = [];
	let pointer = selected.offsetParent;
	while (pointer && container !== pointer && container.contains(pointer)) {
		offsetParents.push(pointer);
		pointer = pointer.offsetParent;
	}
	const top = selected.offsetTop + offsetParents.reduce((prev, curr) => prev + curr.offsetTop, 0);
	const bottom = top + selected.offsetHeight;
	const viewRectTop = container.scrollTop;
	const viewRectBottom = viewRectTop + container.clientHeight;

	if (top < viewRectTop) {
		container.scrollTop = top;
	} else if (bottom > viewRectBottom) {
		container.scrollTop = bottom - container.clientHeight;
	}
}

/**
 * 获取某一个 键名的数组集
 * @param  {Array} data 数组json
 * @param  {Array} name  需要取的键名
 */
export function getLabelArrFun(data, name) {
	// console.log('getLabelArrFun', data, name);
	let labelArr = []
	for (let i in data) {
		labelArr.push(data[i][name])
	}
	return labelArr
}

/**
 * 判断当前是否处于全屏状态
 */
export function checkFullScreen() {
	let isFull =
		document.mozFullScreen ||
		document.fullScreen ||
		//谷歌浏览器及Webkit内核浏览器
		document.webkitIsFullScreen ||
		document.webkitRequestFullScreen ||
		document.mozRequestFullScreen ||
		document.msFullscreenEnabled
	//to fix : false || undefined == undefined
	if (isFull === undefined) {
		isFull = false;
	}
	return isFull;
}

/**
 * 格式化element-ui table
 * @param {Array} data title数据
 */
export function formatTableData(data = []) {
	return data.map((e, key) => ({
		label: e.name,
		prop: e.key,
		// minWidth: e.key == "ranking" ? 80 : 140,
		minWidth: 140,
		sortable: e.sort ? true : false
	}));
}

export function resetFields(fields = {}, ignores = []) {
	if (!fields) return {};
	const type = Object.prototype.toString;
	Object.entries(fields).forEach(([key, value]) => {
		if (!ignores.includes(key)) {
			if (type.call(value) === "[object String]") fields[key] = "";
			if (type.call(value) === "[object Number]") fields[key] = null;
			if (type.call(value) === "[object Array]") fields[key] = [];
			if (type.call(value) === "[object Boolean]") fields[key] = false;
			if (type.call(value) === "[object Null]") fields[key] = null;
			if (type.call(value) === "[object Undefined]") fields[key] = undefined;
			if (type.call(value) === "[object Object]") {
				resetFields(fields[key])
			};
			if (type.call(value) === "[object Function]") fields[key] = null;
		}
	});
	return fields;
};

// 展开子节点
export function flatChilds(list, key = "children") {
	let result = []
	function deep(arr = [], level = 1) {
		arr.forEach(v => {
			result.push({ level, ...v })
			let children = v[key] ?? [];
			if (children.length) {
				deep(children, level + 1);
			};
		});
	}
	deep(list, 1);
	return result;
}

export function filterCity(value, separator = '/') {
	let province = threeLevel.find(item => item.value == value[0]);
	let city = province.children.find(item => item.value == value[1]);
	let area = city.children.find(item => item.value == value[2]);
	return [province.label, city.label, area.label].join(separator);
}

export function numFormat(num) {
	var c = (num.toString().indexOf('.') !== -1) ? num.toLocaleString() : num.toString().replace(
		/(\d)(?=(?:\d{3})+$)/g, '$1,');
	return c;
}

/** *
 * 是否为空
 * @parmas any - val 传进来的值
 */
 const isEmpty = (val) => {
    if (val instanceof Array) {
        if (val.length === 0) return true
    } else if (val instanceof Object) {
        if (!Object.keys(val).length) return true
    } else {
        if (val === 'null' || val === null || val === 'undefined' || val === undefined || val === '') return true
        return false
    }
    return false
}

/** *
 * 对象参数转为url参数
 * @parmas query 拼接得参数对象
 */
 export const parse = (query = {}) => {
    return Object.keys(query)
        .filter(key => !isEmpty(query[key]))
        .reduce((result, key) => {
            const value = query[key]
            // in查询特殊处理
            if (Array.isArray(value) && !isEmpty(value)) {
                return `${result}&${value.reduce((val, cVal) => `${val ? `${val}&` : val}${key}=${cVal}`, '')}`
            }

            // between查询做特殊处理
            if (typeof value === 'object' && !isEmpty(value)) {
                const [start, end] = value
                return `${result}&${key}[]=${start}&${key}[]=${end}`
            }

            return `${result}&${key}=${value}`
        }, '')
        .replace(/^&/, '?')
}
